<template>
  <div class="profile-page">
    <!-- 用户信息头部 -->
    <div class="profile-header" :style="headerStyle">
      <div class="header-background"></div>
      <div class="header-content">
        <div class="user-avatar">
          <img :src="userInfo.avatar || defaultAvatar" alt="用户头像" />
          <van-uploader
            class="avatar-uploader"
            :after-read="uploadAvatar"
            :max-size="2 * 1024 * 1024"
            @oversize="onOversize"
          >
            <van-icon name="photograph" color="#fff" />
          </van-uploader>
        </div>
        <div class="user-info">
          <h2>{{ userInfo.name || '未设置用户名' }}</h2>
          <p class="user-phone"><van-icon name="phone-o" /> {{ userInfo.phone | phoneFilter }}</p>
          <p class="user-balance">
            账户余额: <span>¥{{ userInfo.balance.toFixed(2) }}</span>
          </p>
        </div>
        <van-button class="edit-btn" round size="small" icon="edit" @click="goToEditProfile">
          编辑
        </van-button>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-cards">
      <van-row gutter="10">
        <van-col span="8">
          <div class="stat-card">
            <div class="stat-value">{{ userStats.orderCount }}</div>
            <div class="stat-label">全部订单</div>
          </div>
        </van-col>
        <van-col span="8">
          <div class="stat-card">
            <div class="stat-value">{{ userStats.pendingCount }}</div>
            <div class="stat-label">待处理</div>
          </div>
        </van-col>
        <van-col span="8">
          <div class="stat-card">
            <div class="stat-value">{{ userStats.completedCount }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </van-col>
      </van-row>
    </div>

    <!-- 我的功能列表 -->
    <div class="profile-section">
      <div class="section-title">我的功能</div>
      <van-cell-group :border="false">
        <van-cell title="我的订单" icon="orders-o" is-link @click="goToOrders" />
        <van-cell title="我的钱包" icon="balance-pay" is-link @click="goToWallet">
          <template #right-icon>
            <van-tag type="warning" v-if="userInfo.balance < 100">余额不足</van-tag>
          </template>
        </van-cell>
        <van-cell title="我的地址" icon="location-o" is-link @click="goToAddress" />
      </van-cell-group>
    </div>

    <!-- 系统设置 -->
    <div class="profile-section">
      <div class="section-title">系统设置</div>
      <van-cell-group :border="false">
        <van-cell title="账号与安全" icon="manager-o" is-link @click="goToAccountSecurity" />
        <van-cell title="清除缓存" icon="delete" is-link @click="clearCache">
          <template #right-icon>
            <span class="cache-size">{{ cacheSize }}</span>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <!-- 退出登录按钮 -->
    <div class="logout-section">
      <van-button block round type="default" size="large" @click="handleLogout">
        退出登录
      </van-button>
    </div>

    <!-- 底部导航 -->
    <tabbar active="user" />
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { Toast, Dialog } from 'vant'
import Tabbar from '../components/Tabbar.vue'
import defaultAvatar from '../assets/avatar.png'

// 用户角色类型
type UserRole = 'guest' | 'user' | 'vip' | 'manager' | 'admin'

// 用户信息接口
interface UserInfo {
  id: number
  username: string
  name: string
  phone: string
  email?: string
  avatar: string
  balance: number
  role: UserRole
  warehouseId?: string // 默认冷库ID
  company?: string // 公司名称
}

// 用户统计数据
interface UserStats {
  orderCount: number // 总订单数
  pendingCount: number // 待处理订单数
  completedCount: number // 已完成订单数
  couponCount: number // 优惠券数量
  unreadMsg: number // 未读消息数
}

export default defineComponent({
  name: 'UserProfile',
  components: {
    Tabbar,
  },

  filters: {
    phoneFilter(phone: string): string {
      if (phone && phone.length === 11) {
        return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }
      return phone
    },
  },

  setup() {
    const router = useRouter()
    const userStore = useUserStore()

    // 用户信息
    const userInfo = reactive<UserInfo>({
      id: 1,
      username: 'user123',
      name: '张三',
      phone: '13800138000',
      avatar: '',
      balance: 2480.65,
      role: 'user',
    })

    // 用户统计数据
    const userStats = reactive<UserStats>({
      orderCount: 12,
      pendingCount: 2,
      completedCount: 10,
      couponCount: 3,
      unreadMsg: 5,
    })

    // 缓存大小
    const cacheSize = ref('0KB')

    // 头部样式
    const headerStyle = computed(() => {
      return {
        background: `linear-gradient(to right, #4e54c8, #8f94fb)`,
      }
    })

    // 页面加载时获取用户数据
    onMounted(() => {
      fetchUserData()
      calculateCacheSize()
    })

    // 获取用户数据
    const fetchUserData = () => {
      // 实际项目中应从 store 或 API 获取
      // userStore.userInfo 中获取

      // 模拟从服务器获取数据
      setTimeout(() => {
        userInfo.name = '李冷库'
        userInfo.phone = '13888888888'
        userInfo.balance = 3265.87
        userInfo.role = 'manager'
      }, 300)
    }

    // 计算缓存大小
    const calculateCacheSize = () => {
      // 模拟计算缓存大小
      cacheSize.value = (Math.random() * 10).toFixed(2) + 'MB'
    }

    // 上传头像
    const uploadAvatar = (file: File) => {
      Toast.loading({
        message: '上传中...',
        forbidClick: true,
      })

      // 模拟上传
      setTimeout(() => {
        Toast.clear()
        userInfo.avatar = URL.createObjectURL(file)
        Toast('头像更新成功')
      }, 1500)
    }

    // 文件大小超出限制
    const onOversize = () => {
      Toast('图片大小不能超过 2MB')
    }

    // 清除缓存
    const clearCache = () => {
      Dialog({
        title: '清除缓存',
        message: '确定要清除所有缓存数据吗？',
      }).then(() => {
        Toast.loading({
          message: '清除中...',
          forbidClick: true,
        })

        // 模拟清除缓存
        setTimeout(() => {
          Toast.clear()
          cacheSize.value = '0KB'
          Toast('缓存已清除')
        }, 1000)
      })
    }

    // 导航功能方法
    const goToEditProfile = () => router.push('/profile/edit')
    const goToOrders = () => router.push('/order-list')
    const goToWallet = () => router.push('/wallet')
    const goToAddress = () => router.push('/address')
    const goToAccountSecurity = () => router.push('/account/security')

    // 退出登录
    const handleLogout = () => {
      Dialog({
        title: '确认退出',
        message: '确定要退出当前账号吗？',
      }).then(() => {
        userStore.logout()
        router.replace('/login')
      })
    }

    return {
      userInfo,
      userStats,
      cacheSize,
      headerStyle,
      uploadAvatar,
      onOversize,
      clearCache,
      goToEditProfile,
      goToOrders,
      goToWallet,
      goToAddress,
      goToAccountSecurity,
      handleLogout,
      defaultAvatar,
    }
  },
})
</script>

<style lang="scss" scoped>
.profile-page {
  padding-bottom: 60px; // 底部导航高度
  background-color: #f7f8fa;
  min-height: 100vh;
}

// 头部样式
.profile-header {
  position: relative;
  height: 200px;
  color: white;
  overflow: hidden;

  .header-background {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 100%;
    background: linear-gradient(to right, #4e54c8, #8f94fb);
    z-index: 0;
  }

  .header-content {
    position: relative;
    z-index: 1;
    padding: 30px 20px 20px;
    display: flex;
    align-items: flex-start;
  }

  .user-avatar {
    position: relative;
    width: 70px;
    height: 70px;
    border-radius: 50%;
    border: 3px solid rgba(255, 255, 255, 0.5);
    overflow: hidden;
    background-color: #fff;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .avatar-uploader {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 28px;
      height: 28px;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
  }

  .user-info {
    flex: 1;
    padding-left: 15px;

    h2 {
      font-size: 20px;
      font-weight: bold;
      margin: 5px 0 8px;
    }

    .user-phone,
    .user-balance {
      font-size: 13px;
      display: flex;
      align-items: center;
      margin-bottom: 5px;
      opacity: 0.9;

      .van-icon {
        margin-right: 5px;
      }
    }

    .user-balance span {
      font-weight: bold;
      margin-left: 5px;
    }
  }

  .edit-btn {
    margin-top: 10px;
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.5);
    color: white;
  }
}

// 数据统计卡片
.stats-cards {
  padding: 15px 10px;

  .stat-card {
    background: white;
    border-radius: 8px;
    padding: 15px 10px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .stat-value {
      font-size: 22px;
      font-weight: bold;
      color: #1989fa;
      margin-bottom: 5px;
    }

    .stat-label {
      font-size: 12px;
      color: #969799;
    }
  }
}

// 功能区样式
.profile-section {
  margin: 15px;

  .section-title {
    font-size: 15px;
    color: #969799;
    padding: 10px 0;
    position: relative;
    padding-left: 12px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 3px;
      height: 16px;
      background: #1989fa;
      border-radius: 2px;
    }
  }

  :deep(.van-cell) {
    border-radius: 8px;
    margin-bottom: 8px;

    .van-icon {
      color: #1989fa;
      font-size: 18px;
      margin-right: 10px;
    }

    .van-tag {
      margin-right: 15px;
    }

    .cache-size {
      color: #969799;
      font-size: 14px;
      margin-right: 8px;
    }
  }
}

// 退出登录区域
.logout-section {
  margin: 30px 15px 0;

  .van-button {
    color: #969799;
  }
}
</style>
